package cn.kgc.jdbc;

import cn.kgc.utils.JDBCUtil;

import javax.lang.model.element.VariableElement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author mosin
 * date 2022/2/11
 * @version 1.0
 */
public class JDBCDemo03 {

    public static void main(String[] args) {

        Connection connection = JDBCUtil.getConnection();
        PreparedStatement pstmt = null;
        ResultSet resultSet = null;
        //获取prepareStatement对象时 要对sql 语句进行预编译   相同的操作不会重复的编译  提高效率
        String  sql = "select username ,password from usr where id = ?";
        try {
            pstmt= connection.prepareStatement(sql);//sql预编译
            //设置参数  参数1： 设置参数的索引 （第几个参数）  参数2：设置的参数值
            pstmt.setInt(1, 1);
            //执行sql
             resultSet = pstmt.executeQuery();
            while (resultSet.next()){
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                System.out.println(username+"::"+password);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
                JDBCUtil.closeAll(resultSet, pstmt, connection);
        }

    }
}
